#!/bin/bash
# 双实例安装
source comm.cfg

color_text() {
    local color=$1
    local text=$2
    echo -e "\e[${color}m${text}\e[0m"
}

error() {
    color_text "31" "$1"
}

info() {
    color_text "32" "$1"
}

function n9esystemd() {
cat <<EOF >/etc/systemd/system/n9e.service
[Unit]
Description="n9e.service"
After=network.target

[Service]
Type=simple
ExecStart=${N9E_PATH}/n9e
WorkingDirectory=${N9E_PATH}
Restart=on-failure
SuccessExitStatus=0
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl start  n9e.service
systemctl enable n9e.service
}

function installvm(){
cp victoria-metrics-prod $N9E_PATH
cat <<EOF >/etc/systemd/system/victoriametrics.service
[Unit]
Description="victoriametrics"
After=network.target

[Service]
Type=simple
ExecStart=${N9E_PATH}/victoria-metrics-prod
Restart=on-failure
SuccessExitStatus=0
LimitNOFILE=65536
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=victoriametrics
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl start victoriametrics.service
systemctl enable victoriametrics.service
}

function n9econfset() {
    #sed -i -e '/KeepHours/s/^#\ //' -e '/RotateSize/s/^#\ //' -e '/RotateNum/s/^#\ //' $N9E_PATH/etc/config.toml
    sed -i /Level/s/DEBUG/INFO/ $N9E_PATH/etc/config.toml
    #sed -i /Output/s/stdout/file/ $N9E_PATH/etc/config.toml
    #sed -i /KeepHours/s/4/48/ $N9E_PATH/etc/config.toml
    # 配置mysql
    sed -i /^DSN/s/1234/${ROOT_PASSWORD}/ $N9E_PATH/etc/config.toml
    sed -i /^DSN/s/127.0.0.1/${MYSQL_HOST}/ $N9E_PATH/etc/config.toml
    # 配置redis sentinel 模式
    sed -i 's/^# Password = ".*/Password = "'"$REDIS_PASSWD"'"/' $N9E_PATH/etc/config.toml
    sed -i '/MasterName/s/^#\ //' $N9E_PATH/etc/config.toml
    sed -i "s/^Address = .*/Address = \"$REDIS_SENTINEL_HOST\"/" $N9E_PATH/etc/config.toml
    sed -i '/^RedisType/s/standalone/sentinel/' $N9E_PATH/etc/config.toml
    sed -i "s/127.0.0.1:9090/${N9E01}:9428/" $N9E_PATH/etc/config.toml

    ip a |grep ${N9E01}
    if [ $? -ne 0 ];then
        mysql -uroot -p${ROOT_PASSWORD} < $N9E_PATH/n9e.sql
        info "import n9e db succeed"
	    sed -i "s/127.0.0.1:9090/${N9E02}:9428/" $N9E_PATH/etc/config.toml
	    info "set VictoriaMetrics succeed"
    fi
}


if [[ $# -ne 1 ]]; then
    error "请输入安装夜莺版本"
    exit 1
fi

if [ ! -d "$N9E_PATH" ];then
    mkdir $N9E_PATH -p
fi
# 下载并安装夜莺
wget https://download.flashcat.cloud/n9e-$1-linux-amd64.tar.gz -P $N9E_PATH
if [ $? -ne 0 ];then
    error '下载错误，请检查下载链接是否正常'
    info "https://download.flashcat.cloud/n9e-$1-linux-amd64.tar.gz"
    exit 1
fi
tar xvf $N9E_PATH/n9e-$1-linux-amd64.tar.gz -C $N9E_PATH
# 初始化n9e 的systemd，设置配置文件
n9econfset
n9esystemd
# installvm
# 检查是否启动成功
for i in $(seq 1 6)
do
    ss -tlnp|grep 17000 &> /dev/null
    if [ $? -eq 0 ];then
        info "n9e安装成功"
        info "请浏览器访问：节点IP:17000，默认用户是 root，密码是 root.2020"
        break
    else
        error "Wating n9e start"
        sleep 10
    fi
done
